package cn.tedu.mall.book.filter;

import cn.tedu.mall.book.pojo.vo.AdminLoginVO;
import cn.tedu.mall.book.pojo.vo.UserSimpleVO;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "MyFilter",urlPatterns = "/carts/*")
public class MyFilter implements Filter {
    //当过滤器初始化时执行此方法
    public void init(FilterConfig config) throws ServletException {
        System.out.println("过滤器初始化");
    }
    //当过滤器销毁时执行的方法
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("执行过滤");
        HttpServletRequest st=(HttpServletRequest) request;
        HttpServletResponse se=(HttpServletResponse) response;

        //得到会话对象
        HttpSession session=st.getSession();
        //从会话对象中得到用户登录成功时保存的用户对象
        UserSimpleVO user = (UserSimpleVO) session.getAttribute("user");
        if (user!=null){//代表登录过
            chain.doFilter(request,response);//放行 允许访问资源
        }else { //代表未登录

        }
        //从会话对象中得到管理员登录成功时保存的用户对象
        AdminLoginVO admin=(AdminLoginVO)session.getAttribute("admin");
        if (admin!=null){//代表管理员登录过
            chain.doFilter(request,response);
        }else {

        }

        System.out.println("过滤器执行了");

    }
}
